package com.example.x1c.broadcastbestpractice;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by x1c on 2017/12/21.
 */

public class LoginActivity extends BaseActivity {


    private static final String TAG = "LoginActivity";


    private SharedPreferences pref;

    private SharedPreferences.Editor editor;

    private CheckBox rememberPass;

    private EditText accountEdit;

    private EditText passwordEdit;

    private Button login;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        pref = PreferenceManager.getDefaultSharedPreferences(this);

        rememberPass = findViewById(R.id.remember_pass);

        boolean isRemember = pref.getBoolean("remember_pass", false);

        login = (Button) findViewById(R.id.login);

        accountEdit = findViewById(R.id.account);

        passwordEdit = findViewById(R.id.password);

        if(isRemember){
            String account = pref.getString("account","");
            String password = pref.getString("password", "");
            accountEdit.setText(account);
            passwordEdit.setText(password);
            rememberPass.setChecked(true);

        }

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = accountEdit.getText().toString();
                String password = passwordEdit.getText().toString();
                if(account.equals("admin") && password.equals("123456")){

                    editor = pref.edit();

                    if(rememberPass.isChecked()){
                        editor.putBoolean("remember_pass", true);
                        editor.putString("account", account);
                        editor.putString("password",password);
                        editor.apply();

                        Log.d(TAG, "onClick: 记住了密码，保存。");
                    }else{
                        editor.clear();
                        Log.d(TAG, "onClick: 清除");
                    }

                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();

                }else {
                    Toast.makeText(LoginActivity.this, "account or password is invalid", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}
